<template>
    <ContentField>
        <div class="flex-container">
            <div class="profile-container">
                <!-- 头像部分 -->
                <div class="avatar-container">
                    <img :src="avatarUrl" alt="用户头像" class="avatar" @click="triggerFileInput" />
                    <div class="avatar-overlay">更换头像</div>
                    <input
                        type="file"
                        ref="fileInput"
                        style="display: none"
                        accept="image/*"
                        @change="handleFileUpload"
                    />
                </div>

                <!-- 用户信息部分 -->
                <div class="user-info">
                    <div class="info-item">
                        <span class="label">ID:</span>
                        <span class="value">{{ userId }}</span>
                    </div>

                    <div class="info-item">
                        <span class="label">用户名:</span>
                        <div class="value-container">
                            <span class="value">{{ username }}</span>
                            <button @click="toggleUsernameForm" class="btn-edit">
                                <i class="fas fa-edit"></i>
                            </button>
                        </div>
                    </div>

                    <div class="info-item">
                        <span class="label">游戏积分:</span>
                        <span class="rating">{{ rating }}</span>
                    </div>
                </div>

                <!-- 修改用户名表单 -->
                <div v-if="showUsernameForm" class="action-section">
                    <h3>修改用户名</h3>
                    <input
                        v-model="newUsername"
                        type="text"
                        placeholder="新用户名"
                        class="form-input"
                    />
                    <input
                        v-model="usernamePassword"
                        type="password"
                        placeholder="当前密码"
                        class="form-input"
                    />
                    <div class="form-actions">
                        <button @click="updateUsername" class="btn btn-confirm">确认修改</button>
                        <button @click="toggleUsernameForm" class="btn btn-cancel">取消</button>
                    </div>
                    <div v-if="usernameError" class="error-message">{{ usernameError }}</div>
                    <div v-if="usernameSuccess" class="success-message">{{ usernameSuccess }}</div>
                </div>

                <!-- 修改密码按钮 -->
                <button
                    @click="togglePasswordForm"
                    class="btn btn-password"
                    :class="{ 'btn-active': showPasswordForm }"
                >
                    {{ showPasswordForm ? '关闭修改密码' : '修改密码' }}
                </button>

                <!-- 修改密码表单 -->
                <div v-if="showPasswordForm" class="action-section">
                    <h3>修改密码</h3>
                    <input
                        v-model="oldPassword"
                        type="password"
                        placeholder="旧密码"
                        class="form-input"
                    />
                    <input
                        v-model="newPassword"
                        type="password"
                        placeholder="新密码"
                        class="form-input"
                    />
                    <input
                        v-model="confirmPassword"
                        type="password"
                        placeholder="确认新密码"
                        class="form-input"
                    />
                    <div class="form-actions">
                        <button @click="updatePassword" class="btn btn-confirm">确认修改</button>
                        <button @click="togglePasswordForm" class="btn btn-cancel">取消</button>
                    </div>
                    <div v-if="passwordError" class="error-message">{{ passwordError }}</div>
                    <div v-if="passwordSuccess" class="success-message">{{ passwordSuccess }}</div>
                </div>

                <button
                    type="submit"
                    class="btn btn-warning return-menu-link"
                    @click="$router.push({ name: 'main' })"
                >
                    返回
                </button>
            </div>
        </div>
    </ContentField>
</template>

<script setup>
import ContentField from '@/components/ContentField.vue'
import { useUserStore } from '@/store/user'
import axios from 'axios'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()

// 用户信息
const userId = ref(userStore.id)
const username = ref(userStore.username)
const rating = ref(userStore.rating)
const avatarUrl = ref(userStore.photo)

// 文件上传相关
const fileInput = ref(null)

// 表单控制
const showUsernameForm = ref(false)
const showPasswordForm = ref(false)

// 表单数据
const newUsername = ref('')
const usernamePassword = ref('')
const oldPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')

// 表单状态
const usernameError = ref('')
const usernameSuccess = ref('')
const passwordError = ref('')
const passwordSuccess = ref('')

// 表单操作方法
const toggleUsernameForm = () => {
    showUsernameForm.value = !showUsernameForm.value
    resetUsernameForm()
}

const togglePasswordForm = () => {
    showPasswordForm.value = !showPasswordForm.value
    resetPasswordForm()
}

const resetUsernameForm = () => {
    newUsername.value = ''
    usernamePassword.value = ''
    usernameError.value = ''
    usernameSuccess.value = ''
}

const resetPasswordForm = () => {
    oldPassword.value = ''
    newPassword.value = ''
    confirmPassword.value = ''
    passwordError.value = ''
    passwordSuccess.value = ''
}

const updateUsername = async () => {
    if (!newUsername.value || !usernamePassword.value) {
        usernameError.value = '请填写所有字段'
        return
    }
    try {
        const resp = await axios.post(
            'https://www.xujiaojiaojiao.cn/api/user/account/update-username/',
            { newUsername: newUsername.value, password: usernamePassword.value },
            { headers: { Authorization: `Bearer ${userStore.token}` } }
        )
        if (resp.data.code === 1) {
            usernameSuccess.value = '用户名修改成功'
            userStore.username = newUsername.value
            username.value = newUsername.value
            showUsernameForm.value = false
            resetUsernameForm()
        } else {
            usernameError.value = resp.data.msg
        }
    } catch (e) {
        usernameError.value = '修改失败'
    }
}

const updatePassword = async () => {
    if (!oldPassword.value || !newPassword.value || !confirmPassword.value) {
        passwordError.value = '请填写所有字段'
        return
    }
    try {
        const resp = await axios.post(
            'https://www.xujiaojiaojiao.cn/api/user/account/update-password/',
            {
                oldPassword: oldPassword.value,
                newPassword: newPassword.value,
                confirmPassword: confirmPassword.value,
            },
            { headers: { Authorization: `Bearer ${userStore.token}` } }
        )
        if (resp.data.code === 1) {
            passwordSuccess.value = '密码修改成功，请重新登录'
            setTimeout(() => {
                userStore.fullLogout()
                router.push({ name: 'auth' })
            }, 1500)
        } else {
            passwordError.value = resp.data.msg
        }
    } catch (e) {
        passwordError.value = '修改失败'
    }
}

const triggerFileInput = () => fileInput.value.click()

const handleFileUpload = async (event) => {
    const file = event.target.files[0]
    if (!file) return

    const formData = new FormData()
    formData.append('file', file)

    try {
        const response = await axios.post(
            'https://www.xujiaojiaojiao.cn/api/user/account/upload/',
            formData,
            {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    Authorization: `Bearer ${userStore.token}`,
                },
            }
        )
        if (response.data.code === 1) {
            avatarUrl.value = response.data.data
            userStore.photo = response.data.data
        }
    } catch (error) {
        console.error('头像上传失败:', error)
    }
}
</script>

<style scoped>
/* 新增编辑按钮样式 */
.value-container {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-edit {
    background: none;
    border: none;
    color: var(--text-light);
    cursor: pointer;
    padding: 0.25rem;
    transition: color 0.3s;
}

.btn-edit:hover {
    color: var(--primary-color);
}

.btn-password {
    margin-top: 1.5rem;
    width: 100%;
    color: var(--text-dark);
    border: 1px solid #e2e8f0;
    cursor: pointer;
    border-radius: 8px;
    padding: 0.5rem;
    background: #dfe5ea;
    transition: all 0.2s ease;
}

.btn-password:hover {
    background: #e2e8f0;
}

.btn-active {
    background: var(--primary-color);
    color: var(--text-dark);
}

.form-actions {
    display: flex;
    gap: 1rem;
    margin-top: 1rem;
}

.btn-confirm {
    background: #f1f5f9;
    color: var(--text-dark);
    flex: 1;
    border: 1px solid #e2e8f0;
    cursor: pointer;
}

.btn-cancel {
    background: #f1f5f9;
    color: var(--text-dark);
    flex: 1;
    border: 1px solid #e2e8f0;
    cursor: pointer;
}
.action-section {
    background: white;
    padding: 2rem;
    border-radius: 16px;
    margin-top: 1.5rem;
    width: 100%;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-section h3 {
    color: var(--text-dark);
    margin-bottom: 1rem;
    font-size: 1.2em;
}

.form-input {
    width: 100%;
    padding: 1rem;
    margin-bottom: 1.2rem;
    border: 2px solid #e2e8f0;
    border-radius: 10px;
    transition: all 0.3s ease;
    font-size: 1rem;
}

.form-input:focus {
    border-color: var(--primary-color);
    outline: none;
}

.error-message {
    color: #ef4444;
    margin-top: 0.5rem;
    font-size: 0.9em;
}

.success-message {
    color: #10b981;
    margin-top: 0.5rem;
    font-size: 0.9em;
}

.btn-primary {
    background: var(--primary-color);
    color: white;
    padding: 1rem;
    border-radius: 8px;
    font-weight: 600;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.btn-primary:hover {
    background: var(--secondary-color);
}
/* 新增CSS变量方便管理 */
:root {
    --primary-color: #6366f1; /* 主色调改为柔和的紫色 */
    --secondary-color: #3b82f6; /* 辅色为蓝色 */
    --text-dark: #1e293b;
    --text-light: #64748b;
}

.profile-container {
    max-width: 720px; /* 适当加宽 */
    margin: 2rem auto;
    padding: 2.5rem;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); /* 渐变背景 */
    border-radius: 16px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    overflow: hidden;
}

/* 添加装饰性元素 */
.profile-container::before {
    content: '';
    position: absolute;
    top: -50px;
    right: -50px;
    width: 120px;
    height: 120px;
    background: var(--primary-color);
    opacity: 0.1;
    border-radius: 30px;
    transform: rotate(45deg);
}

.avatar-container {
    position: relative;
    width: 160px; /* 稍大尺寸 */
    height: 160px;
    border-radius: 50%;
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    border: 3px solid white;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
    z-index: 1;
}

.avatar-container:hover {
    transform: scale(1.05);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

.avatar-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.5);
    color: rgb(255, 255, 255);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
    pointer-events: none;
    font-size: 14px;
}

.avatar-container:hover .avatar-overlay {
    opacity: 1;
}

.avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    border: 4px solid #fff;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    object-fit: cover;
}

.user-info {
    background: white;
    padding: 2rem;
    border-radius: 12px;
    margin-top: 2rem;
    width: 100%;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
    position: relative;
    transition: transform 0.3s ease;
}

.user-info:hover {
    transform: translateY(-5px);
}

.info-item {
    margin: 1.2rem 0;
    padding: 0.8rem 1rem;
    border-radius: 8px;
    background: #f8fafc;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: all 0.2s ease;
}

.info-item:hover {
    background: #f1f5f9;
    transform: translateX(10px);
}

.label {
    color: var(--text-light);
    font-weight: 600;
    font-size: 0.95em;
    letter-spacing: 0.3px;
}

.value {
    color: var(--text-dark);
    font-weight: 700;
    font-size: 1.1em;
}

.rating {
    color: #f59e0b;
    position: relative;
    padding-left: 24px;
}

.rating::before {
    content: '★';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    color: #f59e0b;
}

.return-menu-link {
    margin-top: 2rem;
    padding: 0.8rem 2rem;
    background: var(--primary-color);
    color: rgb(19, 17, 17) !important;
    border-radius: 50px;
    text-decoration: none;
    transition: all 0.3s ease;
    box-shadow: 0 4px 6px rgba(99, 102, 241, 0.2);
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.return-menu-link:hover {
    background: var(--secondary-color);
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(59, 130, 246, 0.3);
}

@media (max-width: 640px) {
    .profile-container {
        margin: 1rem;
        padding: 1.5rem;
        border-radius: 12px;
    }

    .avatar-container {
        width: 120px;
        height: 120px;
    }

    .user-info {
        padding: 1.5rem;
    }

    .info-item {
        padding: 0.6rem;
    }
}

/* 新增加载动画 */
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.profile-container {
    animation: fadeIn 0.6s ease-out;
}
</style>
